#!/usr/bin/env perl

# Usage: ./csv_json.pl sheetname < fn.csv > data.json

use strict;
#use Tie::Hash::Indexed;
use Text::CSV::Slurp;
use JSON::XS;

# Determine the spreadsheet name
my $sheetname = $ARGV[0] || '';

# Slurp in file content from stdin
my $csv_text = do { local $/; <STDIN>; };
# We are not able to configure the Text::CSV parser to work correctly with \r\n
# line endings, so we manually change them to Unix line endings which will work.
$csv_text =~ s/\r\n/\n/g;

# Parse each CSV line into a Perl hash object
# Note: hash keys are ordered alphabetcially, but ideally they should be
# ordered as the values in each line
my $csv_objs = [];
$csv_objs = Text::CSV::Slurp->load(string => $csv_text, (
	  binary => 1
	, allow_whitespace => 1
	, escape_char => "\\"
	, empty_is_undef => 1
	, auto_diag => 1
)) or die 'Text/CSV/Slurp died';

# If there is a sheetname, add it as a property for each hash object
if ($sheetname) {
	($_->{Sheetname} = $sheetname) for @$csv_objs;
}

# Encode each CSV line into JSON format
my $json_text = '';
$json_text = JSON::XS->new->utf8->pretty->allow_nonref->encode($csv_objs)
	or die 'JSON/XS died';

# We are not able to configure JSON::XS to encode numbers into numbers
# instead of strings.  Therefore, we replace all numeric strings as
# numbers, eg, ': "-7712.5"' becomes ': -7712.5'
$json_text =~ s/: \s+ "(-*[\d.]+)" /: $1/gx;

print $json_text, "\n";

exit;
